###
    定金入住页面已合并到线下入住中，本页面已经废弃！！！！！
###
angular.module('Controller')
.controller 'QgyEarnestCheckInCtrl', ($scope, $http, $rootScope,qgyApiService, commonConstant, urls, wfAlert, $uibModal, $localStorage)->
    $scope.sexList = commonConstant.numSexList()
    initData=()->
        if $scope.contractNew
            lastApId=$scope.contractNew?.apartmentId
        $scope.contractNew = {
            apartmentId: lastApId
            buildingId: undefined
            floor: undefined
            houseId: undefined
            payWay: undefined
            lease: undefined
            leaseStart: undefined
            created: false
        }

        $scope.checkIn = {
            receptionist: undefined
            buzType:1
            inviteCode:undefined
        }
        $scope.person = {
            customerName: undefined
            customerPhone: undefined
            idCard: undefined
            idcardFront: undefined
            idcardBack: undefined
            sex: 0
        }
        $scope.pay = {
            billId:undefined
            billContent:undefined
            payMoney: undefined
            payType: undefined
            moneyDesc: undefined
        }
        $scope.contractData = undefined
        $scope.cotenant = []
    initData()
    _.defer(()->
        $('#off-idcard-front').unbind()
        $('#off-idcard-front').change(()->
            fileName=$('#off-idcard-front').eq(0).val()
            if(!/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(fileName))
                wfAlert.toastInfo('仅接受图片文件')
                return
            formData = new FormData()
            formData.append('file', $('#off-idcard-front')[0].files[0])
            $http({
                url: urls.backend + urls.imageUploadTo + "/image?token=" + $localStorage['token'],
                method: 'POST'
                headers: {
                    'Content-Type': undefined
                }
                data: formData
                transformRequest: angular.identity
            }).success((resp)->
                if resp.code == 0
                    saveUrl = resp.message.saveUrl + ""
                    if(saveUrl.indexOf("http") == 0)
                        $scope.person.idcardFront = saveUrl
                    else
                        $scope.person.idcardFront = urls.backend + '/public/' + saveUrl
            )
        )
        $('#off-idcard-back').unbind()
        $('#off-idcard-back').change(()->
            fileName=$('#off-idcard-back').eq(0).val()
            console.log()
            if(!/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(fileName))
                wfAlert.toastInfo('仅接受图片文件')
                return
            formData = new FormData()
            formData.append('file', $('#off-idcard-back')[0].files[0])
            $http({
                url: urls.backend + urls.imageUploadTo + "/image?token=" + $localStorage['token'],
                method: 'POST'
                headers: {
                    'Content-Type': undefined
                }
                data: formData
                transformRequest: angular.identity
            }).success((resp)->
                if resp.code == 0
                    saveUrl = resp.message.saveUrl + ""
                    if(saveUrl.indexOf("http") == 0)
                        $scope.person.idcardBack = saveUrl
                    else
                        $scope.person.idcardBack = urls.backend + '/public/' + saveUrl
            )
        )
    )


    $scope.apartmentList = []
    $scope.buildingList = [{id: undefined, name: '未选择'}]
    $scope.floorList = [{id: undefined, name: '未选择'}]
    $scope.houseList = [{id: undefined, houseNo: '未选择'}]
    $scope.payWayList = [{value: undefined, name: '--'}]
    $scope.leaseList = [{value: undefined, name: '--'}]
    $scope.offPayTypeList = commonConstant.offPayTypeList()
    $scope.channelTypeList = commonConstant.chiChannelTypeList()
    loadApartment = ()->
        $scope.apartmentList = []
        $http.get('/apartment', params: {page: 0, size: 999, enabled: true})
        .success (resp)->
            if resp.code == 0
                $scope.apartmentList = $scope.apartmentList.concat(resp.message.content)
                if $scope.apartmentList.length > 0 and $scope.contractNew.apartmentId == undefined
                    $scope.contractNew.apartmentId = $scope.apartmentList[0].id
                    $scope.loadBuilding()
            else
                console.log(resp.message)
        .error (err)->
            console.log(err)
    loadApartment()
    _.extend $scope,
        doCancel: ()->
            initData()
            $scope.resetBuilding()
        resetHouse: ()->
            $scope.contractNew.houseId = undefined
            $scope.houseInfo = undefined
            $scope.houseList = [{id: undefined, houseNo: '未选择'}]
            $scope.payWayList = [{value: undefined, name: '--'}]
            $scope.leaseList = [{value: undefined, name: '--'}]
            $scope.contractNew.payType = undefined
            $scope.housePrice=undefined
        resetBuilding: ()->
            $scope.contractNew.buildingId = undefined
            $scope.resetFloor()
        resetFloor: ()->
            $scope.contractNew.floor = undefined
            $scope.floorList = [{id: undefined, name: '未选择'}]
            $scope.resetHouse()
        loadBuilding: ()->
            return if $scope.doInit
            $scope.buildingList = [{id: undefined, name: '未选择'}]
            reqData = {page: 0, size: 999, apartmentId: $scope.contractNew.apartmentId, sort: 'id,ASC'}
            $http.get('/building', params: reqData)
            .success (resp)->
                if resp.code == 0
                    $scope.buildingList = $scope.buildingList.concat(resp.message.content)
                    $scope.resetBuilding()
        loadFloor: ()->
            return if $scope.doInit
            if $scope.contractNew.buildingId == undefined
                $scope.resetFloor()
            else
                $scope.resetFloor()
                building = _.find($scope.buildingList, (theBd)-> theBd.id == $scope.contractNew.buildingId)
                $scope.floorList = $scope.floorList.concat(building.floorDesc) if building
        loadHouse: ()->
            return if $scope.doInit
            if $scope.contractNew.floor == undefined
                $scope.resetHouse()
                return
            $scope.houseList = [{id: undefined, houseNo: '未选择'}]
            reqData = {
                page: 0, size: 999,
                apartmentId: $scope.contractNew.apartmentId
                buildingId: $scope.contractNew.buildingId
                floor: $scope.contractNew.floor
                status: 1
            }
            $http.get('/house', params: reqData)
            .success (resp)->
                if resp.code == 0
                    $scope.resetHouse()
                    $scope.houseList = $scope.houseList.concat(resp.message.content)
                    if $scope.contractNew.buildingId==$scope.earnestHouse.buildingId
                        $scope.houseList.splice(1,0,$scope.earnestHouse)
        pickHouse: ()->
            if $scope.contractNew.houseId == undefined
                $scope.houseInfo == undefined
                $scope.contractNew.payType = undefined
                $scope.payWayList = [{value: undefined, name: '--'}]
                $scope.leaseList = [{value: undefined, name: '--'}]
            else
                $scope.houseInfo = _.find($scope.houseList, (theRoom)-> theRoom.id == $scope.contractNew.houseId)
                console.log('houseInfo', $scope.houseInfo)
                $scope.payWayList = commonConstant.transferpayWayList($scope.houseInfo.payType)
                $scope.leaseList = commonConstant.leaseList()
                $scope.contractNew.lease = $scope.leaseList[1].value
                if $scope.payWayList.length > 0
                    $scope.contractNew.payWay = $scope.payWayList[0].value
            $scope.getHousePrice()
        uploadIDCFront: ()->
            if !$scope.contractNew.created
                $('input[id=off-idcard-front]').click();
            ''
        uploadIDCBack: ()->
            if !$scope.contractNew.created
                $('input[id=off-idcard-back]').click();
            ''
        offlineCheckIn: ()->
            ''
        offlineCotenant: ()->
            if $scope.contractNew.created
                $scope.openCotenant('view', $scope.cotenant)
            else
                $scope.openCotenant('edit', $scope.cotenant)
        createContract: ()->
            if $scope.contractNew.payWay == 2 && $scope.contractNew.lease == 1
                wfAlert.toastError('付款方式为押一付三时不允许租期少于三个月')
                return
            if $scope.cotenant.length == 0
                wfAlert.toastError('至少包含一个住客的信息')
                return
            if !$scope.person.idcardFront || !$scope.person.idcardBack
                wfAlert.toastError('请上传身份证正反面照片')
                return
            if $scope.housePrice==undefined
                wfAlert.toastError('缺少有效的房间价格信息')
                return
            $scope.contractNew.creating = true
            data = {
                "houseId": $scope.contractNew.houseId, "payWay": $scope.contractNew.payWay,
                "lease": $scope.contractNew.lease,
                "leaseStart": moment($scope.contractNew.leaseStart).format('YYYY-MM-DD'),
                "customerCard": $scope.person.customerCard, "customerName": $scope.person.customerName
                "customerPhone": $scope.person.customerPhone, "sex": $scope.person.sex
                "idcardFront": $scope.person.idcardFront, "idcardBack": $scope.person.idcardBack
#                "payMoney":7200.000,
                "cotenant": $scope.cotenant
            }
            $http.post('/contract', data).success((resp)->
                $scope.contractNew.creating = false
                if resp.code == 0
#后台无电子签名步骤，生成合同后直接调确认接口将合同状态置为待入住
                    $scope.pay.billId=resp.message.billId
                    $scope.pay.billContent=resp.message.billContent
                    $scope.pay.payMoney=resp.message.money
                    console.log('合同生成成功',resp.message)
                    tmp1={"contractPdf":"pdfUrl","signPicture":"signUrl"}
                    $http.put("/contract/confirm/#{resp.message.contractId}",tmp1)
                    .success((confirmResp)->
                        if confirmResp.code==0
                            $rootScope.$broadcast('refresh')
                            wfAlert.toastInfo('合同生成成功')
                            $scope.contractNew.created = true
                            $scope.loadContract(resp.message.contractId)
                    )
                else
                    wfAlert.toastError(resp.message)
            )
        loadContract: (id)->
            return if id == undefined
            $http.get("/contract/#{id}/detail")
            .success((resp)->
                if resp.code == 0
                    $scope.contractData = resp.message
                    $scope.pay.payType = 3
                    console.log('contractData', $scope.contractData)
            )
        confirmPay: ()->
            reqData = {
                payMoney: $scope.pay.payMoney
                payType: $scope.pay.payType
                moneyDesc: $scope.pay.moneyDesc
            }
            $http.put("/bill/#{$scope.pay.billId}/pay", reqData)
            .success((resp)->
                if resp.code == 0
                    wfAlert.toastInfo('确认付款成功')
                    $scope.contractData.status = 4
                else
                    wfAlert.toastError(resp.message)
            )
        getHousePrice:()->
            theData=angular.copy($scope.contractNew)
            if theData and theData.houseId and theData.lease and theData.payWay and theData.leaseStart
                pricePm=qgyApiService.getAsyncHousePrice(theData)
                pricePm.then((data)->
                    $scope.housePrice=data
                )
            else
                $scope.housePrice=undefined
        offlineCheckIn: ()->
            reqData = {
                idcardFront:$scope.contractData.idcardFront,
                idcardBack:$scope.contractData.idcardBack,
                receptionist: $scope.checkIn.receptionist
                buzType: $scope.checkIn.buzType
                inviteCode:$scope.checkIn.inviteCode
            }
            $http.post("/contract/checkIn/#{$scope.contractData.id}", reqData)
            .success((resp)->
                if resp.code == 0
                    $rootScope.$broadcast('refresh')
                    wfAlert.toastInfo('入住成功')
                    $scope.contractData.status=8
            )
        openCotenant: (type, item)->
            modal = showCotenantModal(type, item)
            modal.result.then((modalData)->
                if modalData && type != 'view'
                    $scope.cotenant = modalData
                    console.log($scope.cotenant)
            )
            ''
        fetchUser:()->
            if $scope.person.customerPhone?.length==11
                $http.get('/customerUser',params:{page:0,size:5,phone:$scope.person.customerPhone})
                .success((listResp)->
                    return if listResp.code!=0 || listResp.message.content.length==0
                    $http.get("/customerUser/#{listResp.message.content[0].id}")
                    .success((resp)->
                        return if resp.code!=0
                        userData=resp.message
                        $scope.person.customerName=userData.name
                        $scope.person.customerCard=userData.idcard
                        $scope.person.idcardFront=userData.idcardFront
                        $scope.person.idcardBack=userData.idcardBack
                        if $scope.person.customerName and $scope.person.customerCard and $scope.cotenant?.length==0
                            $scope.cotenant.push({
                                customerName:$scope.person.customerName,
                                customerCard:$scope.person.customerCard
                            })
                    )
                )
        autoInsertContenant:()->
            if $scope.person.customerName and $scope.person.customerCard
                if $scope.cotenant?.length==0
                    $scope.cotenant.push({
                        customerName:$scope.person.customerName,
                        customerCard:$scope.person.customerCard
                    })
                else if $scope.cotenant.length==1
                    cardTmp=_.find($scope.cotenant,(theItem)->theItem.customerCard==$scope.person.customerCard)
                    nameTmp=_.find($scope.cotenant,(theItem2)->theItem2.customerName==$scope.person.customerName)
                    if cardTmp
                        cardTmp.customerName=$scope.person.customerName
                    else if nameTmp
                        nameTmp.customerCard=$scope.person.customerCard
        printContract:()->
            if $scope.contractData and $scope.contractData.contractPdf
                window.open($scope.contractData.contractPdf, '_blank')
            else
                wfAlert.toastError('合同pdf文件未生成')
            ''
    showCotenantModal = (type, data)->
        modal = $uibModal.open({
            animation: true,
            size: 'lg',
            appendTo: $("#modalContent:eq(0)"),
            controller: 'QgyCotenantModalCtrl',
            templateUrl: 'templates/business-manage/cotenant-modal/cotenant-modal.html',
            resolve: {
                items: ()-> {type: type, data: data}
            }
        })
    ##由房态管理页面进入时，带入已有的公寓、楼栋、楼层、房间号、房间信息
    initPageParamsData = (paramData)->
        $scope.contractNew.apartmentId = paramData.apartmentId
        $scope.contractNew.buildingId = paramData.buildingId
        $scope.contractNew.floor = paramData.floor
        $scope.contractNew.houseId = paramData.id
        reqData = {page: 0, size: 999, apartmentId: paramData.apartmentId, sort: 'id,ASC'}
        $scope.doInit = true
        loadHouse1 = ()->
            houseReqData = {
                page: 0, size: 999, status: 1
                apartmentId: $scope.contractNew.apartmentId
                buildingId: $scope.contractNew.buildingId
                floor: $scope.contractNew.floor
            }
            $http.get('/house', params: houseReqData)
            .success (resp)->
                if resp.code == 0
                    $scope.houseList = [{id: undefined, houseNo: '未选择'}]
                    $scope.houseList = $scope.houseList.concat(resp.message.content)
                    $scope.houseList.push paramData
                    $scope.houseInfo = _.find($scope.houseList, (theRoom)-> theRoom.id == $scope.contractNew.houseId)
                    $scope.payWayList = commonConstant.transferpayWayList($scope.houseInfo.payType)
                    $scope.leaseList = commonConstant.leaseList()
                    $scope.contractNew.lease = $scope.leaseList[1].value
                    if $scope.payWayList.length > 0
                        $scope.contractNew.payWay = $scope.payWayList[0].value
                    console.log('注入结果', $scope.contractNew)
                    $scope.doInit = false
        $http.get('/building', params: reqData)
        .success (resp)->
            if resp.code == 0
                $scope.buildingList = [{id: undefined, name: '未选择'}]
                $scope.buildingList = $scope.buildingList.concat(resp.message.content)
                $scope.floorList = [{id: undefined, name: '未选择'}]
                building = _.find($scope.buildingList, (theBd)-> theBd.id == $scope.contractNew.buildingId)
                $scope.floorList = $scope.floorList.concat(building.floorDesc)
                loadHouse1()
        ''
    if $rootScope.pageType == 'earnest-check'
        console.log('定金入住:', $rootScope.pageParams)
        $scope.earnestHouse=angular.copy($rootScope.pageParams.house)
        initPageParamsData( $scope.earnestHouse)
        $scope.earnest=angular.copy($rootScope.pageParams.earnest)
        $scope.person.customerPhone=$scope.earnest.customerPhone
        $scope.fetchUser()
        $rootScope.pageParams = undefined
        $rootScope.pageType = undefined
